package com.tanhua.server.service;

import com.tanhua.admin.service.MqMessageService;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.domain.User;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.vo.ErrorResult;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private MqMessageService mqMessagerService;

    /**
     * 发送六位验证码
     */
    public void sendMsg(String phone) {
        //使用RandomStringUtils工具类生成随机六位数字
        //String code = RandomStringUtils.random(6);
        String code = "123456";
        //调用SmsTemplate对象，发送手机短信
        //smsTemplate.sendSms(phone,code);
        //将验证码存入redis,有效时间设置为5分钟
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }

    public Map loginVerification(String phone, String code) {
        //验证用户验证码是否有效
        String ridesCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        if (StringUtils.isNotEmpty(ridesCode) && !ridesCode.equals(code)) {
            //抛出验证码无效错误
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);

        //判断是否为新用户
        User user = userApi.findByMobile(phone);
        //默认用户日志为登录
        String type = "0101";
        //如果为新用户，添加新用户信息，isNew返回true
        boolean isNew = false;
        if (user == null) {
            //默认用户日志为注册
            type = "0102";
            user = new User();
            user.setMobile(phone);
            //为用户设置初始密码123456
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            //保存用户并返回用户id
            Long userId = userApi.keep(user);
            user.setId(userId);
            isNew = true;
            //为新用户注册环信账号
            Boolean aBoolean = huanXinTemplate.createUser(Constants.HX_USER_PREFIX + userId, Constants.INIT_PASSWORD);
            //如果该用户不存在，则在user列表
            if (!aBoolean) {
                user.setHxUser(Constants.HX_USER_PREFIX + userId);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        mqMessagerService.sendLogService(user.getId(), type, "user", null);
        //使用用户id和用户phone生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);

        //构造返回结构resultMap
        Map resultMap = new HashMap();
        resultMap.put("token", token);
        resultMap.put("isNew", isNew);
        return resultMap;
    }
}
